﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Data;
using System.Web.UI.WebControls;

/// <summary>
///ExcelHandler 的摘要说明
///Excel的处理类
/// </summary>
public class ExcelHandler
{
    private string s_CheckMessage;

	public ExcelHandler()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    public string CheckMessage
    {
        get { return s_CheckMessage; }
        set { if (s_CheckMessage != value) { s_CheckMessage = value; } }
    }
    //读取一个Excel并返回一个DataSet
    public System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
    {
        string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
        OleDbConnection ExcelConn = new OleDbConnection(strCon);
        try
        {
            string strCom = string.Format("SELECT * FROM [Sheet1$]");
            ExcelConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
            DataSet ds = new DataSet();
            myCommand.Fill(ds, "[" + tableName + "$]");
            ExcelConn.Close();
            return ds;
        }
        catch
        {
            ExcelConn.Close();
            return null;
        }
    }
    //检查Excel是否为空和类型是否正确
    public bool CheckExcel(FileUpload f,string fn)
    {
        if (f.HasFile == false)
        {
            s_CheckMessage = "请您选择Excel文件！";
            return false;
        }

        string IsXls = System.IO.Path.GetExtension(f.FileName).ToString().ToLower();
        string FileName = System.IO.Path.GetFileNameWithoutExtension(f.FileName).ToString();

        if (IsXls != ".xls")
        {
            s_CheckMessage = "只可以选择Excel文件!";
            return false;
        }

        if (FileName != fn)
        {
            s_CheckMessage = "请确认您上传的是"+ fn +"文件！";
            return false;
        }
        return true;
    }
}